package cn.livingCloud.service.impl.operation;

import cn.livingCloud.context.BeanProvider;
import cn.livingCloud.dto.ButtonFormDto;
import cn.livingCloud.dto.ButtonFormListDto;
import cn.livingCloud.entity.content.Button;
import cn.livingCloud.repository.ButtonMapper;
import org.springframework.util.StringUtils;

/**
 * Created by sujiantang on 2016/1/7.
 */
public class ButtonFormListDtoUpdater {

    private transient ButtonMapper mapper = BeanProvider.getBean(ButtonMapper.class);
    private ButtonFormListDto formListDto;

    public ButtonFormListDtoUpdater(ButtonFormListDto formListDto) {
        this.formListDto = formListDto;
    }

    public void update() {
        if (StringUtils.isEmpty(formListDto.getUuid())) {
            createNewButton();
        } else {
            updateButtons();
        }
    }

    private void updateButtons() {
        Button button = mapper.findButtonByUuid(formListDto.getUuid());
        updateButton(button, formListDto);
        for (ButtonFormDto formDto : formListDto.getButtonList()) {
            updateButton(mapper.findButtonByUuid(formDto.getUuid()), formDto);
        }
    }

    private void updateButton(Button button, ButtonFormDto formDto) {
        button.setName(formDto.getName())
                .setType(formDto.getType())
                .setKey(formDto.getKey())
                .setUrl(formDto.getUrl());
        mapper.update(button);
    }

    private void createNewButton() {
        Button button = new Button()
                .setParentId(formListDto.getParent_id())
                .setName(formListDto.getName())
                .setType(formListDto.getType())
                .setKey(formListDto.getKey())
                .setUrl(formListDto.getUrl());
        mapper.save(button);
    }
}
